<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadFilled, SuccessFilled } from '@element-plus/icons-vue';
import { uploadToQiniu } from '@/utils/qiniu';

const props = defineProps({
  maxSize: {
    type: Number,
    default: 500 * 1024 * 1024 // 默认500MB
  },
  value: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['upload-success', 'update:value']);

const videoUrl = ref(props.value || '');
const uploadProgress = ref(0);
const isUploading = ref(false);
const uploadSuccess = ref(false); // 新增上传成功状态
const uploadObservable = ref(null);
const uploadedSize = ref('0 KB');
const totalSize = ref('0 KB');
const fileInputRef = ref(null);

// 获取视频时长
const videoDuration = ref(0); // 新增视频时长字段
const videoElement = ref(null); // 用于获取视频时长的隐藏视频元素

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化视频时长为 "分:秒" 格式
const formatDuration = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
};

// 获取视频时长
const getVideoDuration = (file) => {
  return new Promise((resolve) => {
    // 创建一个临时的URL以加载视频
    const videoURL = URL.createObjectURL(file);
    
    // 创建一个临时的video元素来获取时长
    const tempVideo = document.createElement('video');
    tempVideo.addEventListener('loadedmetadata', () => {
      // 获取视频时长（秒）
      const duration = tempVideo.duration;
      // 释放URL对象
      URL.revokeObjectURL(videoURL);
      resolve(duration);
    });
    
    // 加载视频
    tempVideo.src = videoURL;
  });
};

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  // 重置上传成功状态
  uploadSuccess.value = false;
  
  // 文件类型检查
  if (!file.type.startsWith('video/')) {
    ElMessage.error('请选择视频文件');
    return;
  }
  
  // 文件大小检查
  if (file.size > props.maxSize) {
    const maxSizeMB = props.maxSize / (1024 * 1024);
    ElMessage.error(`视频大小不能超过 ${maxSizeMB}MB`);
    return;
  }
      // 获取视频时长
      const duration = await getVideoDuration(file);
    videoDuration.value = duration;

  // 开始上传
  isUploading.value = true;
  uploadProgress.value = 0;
  totalSize.value = formatFileSize(file.size);
  
  try {


    // 上传视频到七牛云
    const result = await uploadToQiniu(file, 'video', (percent, loaded) => {
      // 更新上传进度，确保不超过100%
      uploadProgress.value = Math.min(percent, 100);
      
      // 计算已上传大小，如果loaded不可用，则使用百分比计算
      const calculatedBytes = loaded !== undefined ? loaded : (percent / 100 * file.size);
      
      // 确保显示的上传大小不会超过总大小
      const bytesToShow = Math.min(calculatedBytes, file.size);
      uploadedSize.value = formatFileSize(bytesToShow);
      
      // 如果进度达到100%，确保显示的大小是文件的实际大小
      if (percent >= 100) {
        uploadedSize.value = totalSize.value;
      }
    });
    
    // 确保进度条显示100%
    uploadProgress.value = 100;
    uploadedSize.value = totalSize.value;
    
    // 上传完成
    videoUrl.value = result.url;
    emit('upload-success', result.url, videoDuration.value);
    emit('update:value', result.url);
    
    // 设置上传成功状态
    uploadSuccess.value = true;
    isUploading.value = false;
    
    ElMessage.success('视频上传成功');
    
  } catch (error) {
    isUploading.value = false;
    uploadProgress.value = 0;
    uploadSuccess.value = false;
    ElMessage.error('视频上传失败，请重试');
    console.error('视频上传失败:', error);
  } finally {
    // 重置文件输入框，允许重新选择相同文件
    if (fileInputRef.value) {
      fileInputRef.value.value = '';
    }
  }
};

// 取消上传
const cancelUpload = () => {
  if (uploadObservable.value && typeof uploadObservable.value.unsubscribe === 'function') {
    uploadObservable.value.unsubscribe();
    uploadObservable.value = null;
  }
  isUploading.value = false;
  uploadProgress.value = 0;
  uploadedSize.value = '0 KB';
  ElMessage.info('已取消上传');
  
  // 重置文件输入框
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
};

// 重新上传
const reupload = () => {
  videoUrl.value = '';
  videoDuration.value = 0; // 重置视频时长
  uploadSuccess.value = false;
  emit('upload-success', '', 0);
  emit('update:value', '');
  
  // 重置文件输入，允许重新选择相同文件
  if (fileInputRef.value) {
    fileInputRef.value.value = '';
  }
};

// 监听拖拽事件
const handleDragOver = (e) => {
  e.preventDefault();
  e.stopPropagation();
};

const handleDrop = (e) => {
  e.preventDefault();
  e.stopPropagation();
  
  if (isUploading.value) return;
  
  const files = e.dataTransfer.files;
  if (files.length > 0) {
    // 模拟文件选择事件
    handleFileChange({ target: { files } });
  }
};

// 暴露方法给父组件
defineExpose({
  reupload
});
</script>

<template>
  <div class="uploader-container">
    <div class="uploader-title">视频上传</div>
    
    <!-- 上传前的状态 -->
    <div 
      v-if="!uploadSuccess && !isUploading" 
      class="upload-area"
      @click="fileInputRef.click()"
      @dragover="handleDragOver"
      @drop="handleDrop"
    >
      <el-icon class="upload-icon"><UploadFilled /></el-icon>
      <div class="upload-tip">点击或拖拽视频文件到此区域</div>
      <div class="upload-sub-tip">支持 MP4、WebM 格式，最大 {{ props.maxSize / (1024 * 1024) }}MB</div>
      <input 
        ref="fileInputRef"
        type="file" 
        class="file-input"
        accept="video/mp4,video/webm" 
        @change="handleFileChange"
      >
    </div>
    
    <!-- 上传中的状态 -->
    <div v-else-if="isUploading" class="uploading-area">
      <div class="progress-info">
        <div class="progress-title">视频上传中</div>
        <el-progress 
          type="circle" 
          :percentage="Math.floor(uploadProgress)" 
          :stroke-width="10"
          :status="uploadProgress < 100 ? 'primary' : 'success'"
          class="progress-circle"
        />
        <div class="progress-details">
          <div class="progress-detail-item">
            <span class="label">已上传/总大小:</span>
            <span class="value">{{ uploadedSize }} / {{ totalSize }}</span>
          </div>
        </div>
      </div>
      <el-button @click="cancelUpload" type="danger" plain>取消上传</el-button>
    </div>
    
    <!-- 上传成功的状态 -->
    <div v-else class="success-area">
      <el-icon class="success-icon"><SuccessFilled /></el-icon>
      <div class="success-message">视频上传成功</div>
      <div class="success-submessage">
        视频时长: {{ formatDuration(videoDuration) }} | 视频将在提交发布后显示
      </div>
      <el-button @click="reupload" type="primary" plain class="reupload-btn">重新上传</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.uploader-container {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  height: 320px;
  display: flex;
  flex-direction: column;
  background-color: white;
}

.uploader-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.upload-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
  
  &:hover {
    border-color: #1890ff;
    
    .upload-icon {
      color: #1890ff;
    }
    
    .upload-tip {
      color: #1890ff;
    }
  }
}

.upload-icon {
  font-size: 48px;
  color: #999;
  margin-bottom: 16px;
  transition: color 0.3s;
}

.upload-tip {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  transition: color 0.3s;
}

.upload-sub-tip {
  font-size: 12px;
  color: #999;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
  pointer-events: none;
}

.uploading-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.progress-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
}

.progress-circle {
  margin-bottom: 20px;
}

.progress-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 16px;
  width: 100%;
  max-width: 300px;
}

.progress-detail-item {
  display: flex;
  justify-content: space-between;
  color: #666;
  
  .label {
    font-size: 14px;
    color: #888;
  }
  
  .value {
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }
}

/* 新的上传成功区域样式 */
.success-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f6f9ff;
  border-radius: 6px;
  border: 1px solid #e6f0fe;
}

.success-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 16px;
}

.success-message {
  font-size: 18px;
  font-weight: 500;
  color: #67c23a;
  margin-bottom: 8px;
}

.success-submessage {
  font-size: 14px;
  color: #909399;
  margin-bottom: 24px;
}

.reupload-btn {
  margin-top: 8px;
}
</style>